package com.aspire.wap.core.esi;

import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * EsiUtils工具类
 * 
 * @author  wangxinning
 * @version 1.1, 05/12/2010
 * @since   JDK1.5
 * @deprecated
 */
public class EsiUtils {

	private static final Log log = LogFactory.getLog("esidev");
	
	/**
	 * 清缓存通用方法
	 * 
	 * @param  esihosts ESI服务器host
	 * @param  esiport ESI服务器port
	 * @param  key 缓存key
	 * @param  apphosts 应用host
	 * @param  appport 应用port 
	 * 
	 * @return  true 清除成功
	 * 			false 清除失败，原因可能是 参数为空或缓存中没有这个key
	 */
	public static boolean clearESICache(String esihosts, int esiport,
			String key, String apphosts, int appport) throws IOException {

		if (StringUtils.isNotEmpty(esihosts) && StringUtils.isNotEmpty(key)
				&& StringUtils.isNotEmpty(apphosts)) {
			
			String command = "PURGE " + key + " HTTP/1.1 \r\nHOST: " + apphosts
					+ (appport != -1 ? ":" + Integer.toString(appport) : "")
					+ "\r\n\r\n";

			boolean bol = EsiUtils.clearESICache(esihosts, esiport, command);
			log.info( bol + "|esihosts:" + esihosts + "|esiport:" + esiport + "|command:" + StringUtils.trimToEmpty(command) );
			return bol;

		} else {
			
			return false;
			
		}
	}

	/**
	 * 根据清除命令清空缓存
	 * 
	 * @param  esihosts ESI服务器host
	 * @param  esiport ESI服务器port
	 * @param  command 清空命令
	 * 
	 * @return  true 清除成功
	 * 			false 清除失败，原因可能是 参数为空或缓存中没有这个key
	 */
	public static boolean clearESICache(String esihosts, int esiport,
			String command) throws IOException {

		if (StringUtils.isNotEmpty(esihosts) && StringUtils.isNotEmpty(command)) {
			
			Socket socket = new Socket(esihosts, esiport);
			OutputStream outputStream = socket.getOutputStream();
			outputStream.write(command.getBytes());
			outputStream.flush();
			
			String retStr = IOUtils.toString(socket.getInputStream());
			//System.out.println(retStr);
			outputStream.close();
			
			if( StringUtils.isNotEmpty(retStr) && retStr.indexOf("200") != -1 )
			{
				return true;
			}
			else
			{
				return false;
			}
			
		} else {
			
			return false;
			
		}
	}
	
	
	public static String makeEsiUrl( String esiurl, int asivar , String esikeys, String tagParam, Map paramMap )
	{
		String retKey = esiurl;
		retKey = addParam(retKey, EsiObject.Param_ver , Integer.toString(asivar));
		
		//增加tag定义的参数
		if( StringUtils.isNotEmpty(tagParam) )//类似格式：tl1=预订,flag=wodeshuju,esitagID=569
		{
			String[] parameter = tagParam.split(",");
			if (parameter != null && parameter.length > 0) {
				
				for (int i = 0; i < parameter.length; i++) {
					if (parameter[i].indexOf("=") != -1) {
						String tempKey = parameter[i].substring(0,
								parameter[i].indexOf("="));
						String tempValue = parameter[i]
								.substring(parameter[i].indexOf("=") + 1);
						
						if( paramMap != null && paramMap.get(tempKey) != null )//以Map的参数为准
						{
							tempValue = (String)paramMap.get(tempKey);
						}

						retKey = addParam(retKey, tempKey, tempValue);
					
					}
				}
			}
		}		
		
		//增加keys中定义的参数
		if( StringUtils.isNotEmpty(esikeys) && paramMap != null )
		{
			String[] parameter = esikeys.split(",");
			if (parameter != null && parameter.length > 0) {
				
				for (int i = 0; i < parameter.length; i++) {
					
					if( paramMap.get(parameter[i]) != null )//以Map的参数为准
					{
						retKey = addParam(retKey, parameter[i] , (String)paramMap.get(parameter[i]));
					}					
				}				
			}
		}
		
		return retKey;
	}
	
	
	public static String addParam(String url, String key, String value) {
		String retUrl = url;

		try {
			if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(key)
					&& StringUtils.isNotEmpty(value)) {

				if (url.indexOf("?") != -1) {
					retUrl += "&" + key + "="
							+ URLEncoder.encode(value, "utf-8");
				} else {
					retUrl += "?" + key + "="
							+ URLEncoder.encode(value, "utf-8");
				}

			}
		} catch (Exception e) {

		}

		return retUrl;
	}
	
	

	 public static void main(String[] args) throws Exception {
	
	 String keys =
	 "http://192.168.1.199/fdsfsdf/dsadasd/front/esi/random8.jsp?a=pass.do&asi_ver=1&tl1=%E9%A2%84%E8%AE%A2&flag=wodeshuju&esitagID=569&postarg=c2NvZGU9MDAwMDAx&";

	 URL ur = new URL(keys);
	 
	 System.out.println(ur.getHost());
	 System.out.println(ur.getPort());
	 System.out.println(ur.getPath());
	 System.out.println(ur.getQuery());
	 
	 System.out.println(ur.getPath() + "?" + ur.getQuery());
	 
	 
	String key = keys.substring(keys.indexOf("//") + 2);
	key = key.substring(key.indexOf("/"));
	System.out.println(key);
	 
	 //	 
//	 System.out.println(EsiUtils.clearESICache("172.20.200.12", 8080, key, "10.2.5.182",80));
	
//		 BASE64Decoder decoder = new BASE64Decoder();
//
//			try {
//				String sss = "bmljaz1rZWtlJmdlbmRlcj0xJnllYXI9MTk4MCZtb250aD0wMSZkYXk9MDEmYmxvb2R0eXBlPTEmaGVpZ2h0PTE4MCZ3ZWlnaHQ9NjgmaG9iYnk9MTA=";
//				byte[] bbb = decoder.decodeBuffer(sss);
//				sss = new String(bbb);
//				
//				System.out.println(sss);
//			}
//			catch( Exception e )
//			{
//				
//			}
//		 
		 
	 }

}